/*
Copyright (c) 2010 Bryce Alcock

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.com

 */

/*
 * ForwarderView.java
 *
 * Created on Oct 9, 2010, 1:21:36 PM
 */
package com.ecocrypt.proxy.forwarder.gui;

import com.ecocrypt.environment.Info;
import com.ecocrypt.proxy.forwarder.remote.ForwarderDestination;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Bryce Alcock
 */
public class RemoteForwarderView extends javax.swing.JFrame implements ListSelectionListener {

    //+---------------------------------------------------------------------
    //
    //  STRUCTURE:
    //  JFrame
    //  +|(ContentPane)
    //  mainPanel+ (JPanel)
    //           |-splitPane+ (JSplitPane)
    //                      |- tableScrolPane+ (JScrolPane)
    //                                       |-  ForwardSeverTable (JTable)
    //                      |- cardPanelForwarderPanes+ (JPanel)
    //                                             |- TabbedPane[s]+ (JTabbedPane)
    //                                                             |- ForwarderTopPanel
    //+---------------------------------------------------------------------
    private JPanel mainPanel;
    private JSplitPane splitPane;
    private JScrollPane tableScrollPane;
    private JTable forwarderServerTable;
    private JPanel cardPanelForwarderPanes;
    private CardLayout cardLayout;
    private JMenuBar menuBar;
    private JMenu destinationsMenu;
    private JMenuItem addDestinationMenuItem;
    private MenuActionListener menuActionListener = new MenuActionListener(this);
    private RemoteForwardDestinationTableModel tableModel = null;
    private HashMap<ForwarderDestination, JTabbedPane> destinationPanes = new HashMap<ForwarderDestination, JTabbedPane>();
    //There can only be one of these, and therefore this is a singleton.
    private static RemoteForwarderView instance;

    public static RemoteForwarderView getInstance() {

	// We do not have to worry about double check lock issue
	// because this is a single threaded applicaiton the first time
	// This method is called.
	if (instance == null) {
	    instance = new RemoteForwarderView();
	}
	return instance;
    }

    public void updateDestinationTable() {
	if (tableModel != null) {
	    tableModel.updateTable();
	}
    }

    /** Creates new form ForwarderView */
    private RemoteForwarderView() {
	initComponents();
	forwarderServerTable.getSelectionModel().addListSelectionListener(this);
    }

    public void setTableModel(RemoteForwardDestinationTableModel tm) {
	tableModel = tm;
	forwarderServerTable.setModel(tm);
    }

    public void addRemoteFowardDestination(ForwarderDestination fd) {
	if (tableModel == null) {
	    setTableModel(new RemoteForwardDestinationTableModel());
	}
	tableModel.addDestination(fd);
	if (!destinationPanes.containsKey(fd)) {
	    JTabbedPane pane = new JTabbedPane();
	    destinationPanes.put(fd, pane);
	    cardPanelForwarderPanes.add(pane, fd.toString());
	}
    }

    public void addFowarderPanelTop(ForwarderDestination fd, ForwarderPanelTop fpt) {
	JTabbedPane pane = destinationPanes.get(fd);
	if (pane == null) {
	    addRemoteFowardDestination(fd);
	    pane = destinationPanes.get(fd);
	}

	if (fpt != null) {
	    if (pane.indexOfTab(fpt.getTitle()) < 0) {
		pane.addTab(fpt.getTitle(), fpt);
	    }else{
		pane.remove(pane.indexOfTab(fpt.getTitle()));
		pane.addTab(fpt.getTitle(), fpt);
	    }
	}
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {


	mainPanel = new JPanel();
	mainPanel.setLayout(new BorderLayout());
	splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
	tableScrollPane = new JScrollPane();
	forwarderServerTable = new JTable();
	cardPanelForwarderPanes = new JPanel();
	cardLayout = new CardLayout();
	cardPanelForwarderPanes.setLayout(cardLayout);

	tableScrollPane.getViewport().add(forwarderServerTable);
	splitPane.add(tableScrollPane, JSplitPane.TOP);
	splitPane.add(cardPanelForwarderPanes, JSplitPane.BOTTOM);
	mainPanel.add(splitPane, BorderLayout.CENTER);



	menuBar = new JMenuBar();
	destinationsMenu = new JMenu("Destinations");
	addDestinationMenuItem = new JMenuItem("Item");

	menuBar.add(destinationsMenu);
	destinationsMenu.add(addDestinationMenuItem);
	addDestinationMenuItem.setActionCommand("Add Destination");
	addDestinationMenuItem.addActionListener(menuActionListener);


	this.setJMenuBar(menuBar);




	this.getContentPane().add(mainPanel);
	this.pack();

	this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String args[]) {
	RemoteForwarderView rfv = new RemoteForwarderView();
	RemoteForwardDestinationTableModel rfdtm = new RemoteForwardDestinationTableModel();
	rfv.setTableModel(rfdtm);
	rfv.setVisible(true);
    }

    public void valueChanged(ListSelectionEvent e) {

	if (forwarderServerTable.getSelectedRow() > -1) {

	    int selectedRow = forwarderServerTable.getSelectedRow();



	    //  If we are in Java1.6 or higher, we are using the JVM's JTable Row Sorter.
	    //  We will use reflection to dynamically invoke the Row Conversion method.
	    //  That method does not exist in Java versions before 1.6.
	    if (Info.isMinVersion()) {
		Class partypes[] = new Class[1];
		partypes[0] = Integer.TYPE;
		Object arglist[] = new Object[1];
		arglist[0] = selectedRow;
		try {
		    // Future Enhancement.
		    //  This method object could be Cached for performance improvements.
		    Method meth = forwarderServerTable.getClass().getMethod("convertRowIndexToModel", partypes);
		    selectedRow = (Integer) meth.invoke(forwarderServerTable, arglist);

		} catch (IllegalAccessException ex) {
		    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
		} catch (IllegalArgumentException ex) {
		    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
		} catch (InvocationTargetException ex) {
		    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
		} catch (NoSuchMethodException ex) {
		    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
		} catch (SecurityException ex) {
		    Logger.getLogger(ForwarderPanelTop.class.getName()).log(Level.SEVERE, null, ex);
		}
	    }
	    RemoteForwardDestinationTableModel rfdtm = (RemoteForwardDestinationTableModel) forwarderServerTable.getModel();
	    ForwarderDestination fd = rfdtm.getObjectAtLocation(selectedRow);
	    cardLayout.show(cardPanelForwarderPanes, fd.toString());

	}
    }
}
